<?php

namespace App\Handlers;

use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;

class ImageUploadHandler {
    protected $allowd_ext = ['png', 'jpg', 'jpeg', 'gif'];

    public function save($file, $folder, $file_prefix, $max_width = false,$unlink=false) {
        $folder_name = "uploads/images/$folder/" . date('Ym/d', time());
        $upload_path = public_path() . '/' . $folder_name;
        $extension = strtolower($file->getClientOriginalExtension()) ?: 'png';
        $filename = md5($file_prefix . time()) . '.' . $extension;

        if (!in_array($extension, $this->allowd_ext)) {
            return false;
        }
        $file->move($upload_path, $filename);
        if ($max_width && $extension != 'gif') {
            $this->reduceSize($upload_path.'/'.$filename,$max_width);
        }
        if($unlink){
            //删除图片
            $this->delOldImage($file_prefix,$upload_path);
        }
        return [
            'path' => config('app.url') . "/$folder_name/$filename"
        ];
    }

    public function reduceSize($file_path, $max_width) {
        $image = Image::make($file_path);
        $image->resize($max_width, null, function ($obj) {
            $obj->aspectRatio();
            $obj->upsize();
        });
        $image->save();
    }
    public function delOldImage($user_id,$upload_path){
        //获取旧的图片
        $user = DB::table('users')->find($user_id);
        if($user){
            $userAvatar = $user->avatar;
            $picArr = explode('/',$userAvatar);
            $old_file = array_pop($picArr);
            @unlink($upload_path.'/'.$old_file);
        }
    }
}
